package com.codi.bus.core.service.impl;

import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.core.dao.SysFileNewDao;
import com.codi.bus.core.domain.SysFileNew;
import com.codi.bus.core.service.EmailService;
import com.codi.bus.core.vo.MailModel;
import com.codi.superman.base.service.SysFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.*;

@Service("emailService")
public class EmailServiceImpl implements EmailService{
    @Resource(name = "javaMailSender")
    private JavaMailSender javaMailSender;

    @Resource(name = "simpleMailMessage")
    private SimpleMailMessage simpleMailMessage;

//    @Resource(name = "sysFileDaoNew")
//    private SysFileDao sysFileDao;
    @Resource
    private SysFileNewDao sysFileNewDao;

    private static final Logger logger = LoggerFactory.getLogger(ClientServiceImpl.class);

    @Override
    public void emailManage(String toEmailAddress) {
        MailModel mail = new MailModel();

        mail.setToEmails(toEmailAddress);

        //附件
        Map<String, String> attachments = new HashMap<>();
//        attachments.put("清单.xlsx",excelPath+"清单.xlsx");
        mail.setAttachments(attachments);

        //内容
        StringBuilder builder = new StringBuilder();

        String context = "<!DOCTYPE html>\n" +
            "<html lang=\"en\">\n" +
            "<head>\n" +
            "    <meta charset=\"UTF-8\">\n" +
            "    <title>Title</title>\n" +
            "    <style>\n" +
            "        * {\n" +
            "            margin: 0;\n" +
            "            padding: 0;\n" +
            "        }\n" +
            "        div{\n" +
            "            padding-left: 54px;\n" +
            "            padding-right: 108px;\n" +
            "        }\n" +
            "        p {\n" +
            "            font-size: 27px;\n" +
            "        }\n" +
            "\n" +
            "        .text1 {\n" +
            "            padding-left: 54px;\n" +
            "        }\n" +
            "\n" +
            "        .text2 {\n" +
            "            padding-left: 108px;\n" +
            "        }\n" +
            "        .text3{\n" +
            "            /*text-align: right;*/\n" +
            "            padding-left: 54px;\n" +
            "        }\n" +
            "    </style>\n" +
            "</head>\n" +
            "<body>\n" +
            "<div>\n" +
            "    <p>尊敬的客户您好：</p>\n" +
            "    <br>\n" +
            "    <p class='text1'>感谢选择科地基金！</p>\n" +
            "    <br>\n" +
            "    <p class='text1'>您需要准备的证件如下：</p>\n" +
            "    <br>\n" +
            "    <p class='text2'>1. 营业执照扫描件；</p>\n" +
            "    <br>\n" +
            "    <p class='text2'>2. 法定代表人身份证（正反面）扫描件；</p>\n" +
            "    <br>\n" +
            "    <p class='text2'>3. 银行账户证明文件，出具“账户名称、银行账号、开户行名称”信息，并加盖银行业务章；</p>\n" +
            "    <br>\n" +
            "    <p class='text2'>4. 经办人身份证（正反面）扫描件；</p>\n" +
            "    <br>\n" +
            "    <p class='text2'>5.《基金业务授权书》、《预留印鉴卡》可在附件中查看。烦请打印填写并加盖公章及法定代表人签章后，与其他开户材料一起发送至 kh666@cd121.com完成企业开户流程。</p>\n" +
            "    <br>\n" +
            "    <p class='text3'>以上材料的填写示例，请在科地基金APP上查看。如有任何疑问，请致电0571-86915761</p>\n" +
            "    <br>\n" +
            "    <p class='text3'>祝您生活愉快！</p>\n" +
            "    <br>\n" +
            "    <p class='text3'>杭州科地瑞富基金销售有限公司</p>\n" +
            "</div>\n" +
            "</body>\n" +
            "</html>";


        builder.append(context);
        String content = builder.toString();

        mail.setContent(content);

        sendEmail(mail);
    }

    @Override
    public boolean sendEmail(MailModel mail) {
        // 建立邮件消息
        MimeMessage message = javaMailSender.createMimeMessage();

        MimeMessageHelper messageHelper;

        try {
            messageHelper = new MimeMessageHelper(message, true, "UTF-8");
            // 设置发件人邮箱
            if (mail.getEmailFrom() != null) {
                messageHelper.setFrom(mail.getEmailFrom());
            } else {
                messageHelper.setFrom(simpleMailMessage.getFrom());
            }

            // 设置收件人邮箱
            if (mail.getToEmails() != null) {
                String[] toEmailArray = mail.getToEmails().split(";");
                List<String> toEmailList = new ArrayList<>();
                if (null == toEmailArray || toEmailArray.length <= 0) {
//                    throw new SimpleExc("收件人邮箱不得为空！");
                } else {
                    for (String s : toEmailArray) {
                        if (s != null && !s.equals("")) {
                            toEmailList.add(s);
                        }
                    }
                    if (null == toEmailList || toEmailList.size() <= 0) {
//                        throw new SimpleException("收件人邮箱不得为空！");
                    } else {
                        toEmailArray = new String[toEmailList.size()];
                        for (int i = 0; i < toEmailList.size(); i++) {
                            toEmailArray[i] = toEmailList.get(i);
                        }
                    }
                }
                messageHelper.setTo(toEmailArray);
            } else {
                messageHelper.setTo(simpleMailMessage.getTo());
            }

            // 邮件主题
            if (mail.getSubject() != null) {
                messageHelper.setSubject(mail.getSubject());
            } else {

                messageHelper.setSubject(simpleMailMessage.getSubject());
            }

            // true 表示启动HTML格式的邮件
            messageHelper.setText(mail.getContent(), true);


            // 添加附件
            String[] attchments = GlobalConstant.EMAIL_ATTACHMENT;

            if (attchments != null) {
                for (String attachment : attchments) {
                    org.springframework.core.io.Resource resource = new ClassPathResource("emailAttach/" + attachment);

                    FileSystemResource fileSystemResource = new FileSystemResource(resource.getFile());
                    messageHelper.addAttachment(attachment, fileSystemResource);
                }
            }

            messageHelper.setSentDate(new Date());
            // 发送邮件
            javaMailSender.send(message);


            logger.info("------------发送邮件完成----------");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return false;
    }
}
